<?php

class Authorization
{
    const USER_SESSION = 'logged_user';
    private $user;
    private $loaded;
    
    private function load(){
        $this->user = false;
        if(isset($_SESSION[self::USER_SESSION])){
            $user = UserTable::getInstance()->findOneBy('id', $_SESSION[self::USER_SESSION]);
            if($user){
                $this->user = $user;
                $this->loaded = true;
            }
        }
    }
    
    private function __construct(){
        $this->loaded = false;
        $this->load();
    }
    
    public static function getInstance(){
        static $instance;
        if(!isset($instance)){
            $instance = new self();
        }
        return $instance;
    }
    
    public function create($login, $password){
        $user = UserTable::getInstance()->findOneBy('name', $login);
        if($user){
            if($user->getPassword() == $password){
                $this->user = $user;
                $_SESSION[self::USER_SESSION] = $user->getId();
                $this->loaded = true;
                return true;
            }
        }
        return false;
    }
    
    public function isExists(){
        return $this->loaded;
    }
    
    public function delete(){
        unset($_SESSION[self::USER_SESSION]);
        unset($this->user);
    }
    
    public function getUser(){
        return $this->user;
    }
}
